<?php
/**
 * Created by PhpStorm.
 * User: poptser@foxmail.com
 * Date: 2018/3/13
 * Time: 14:52
 */
namespace App\Http\Controllers\Sorting;
use App\Http\Controllers\ApiController;


use GuzzleHttp\Client;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;



class LoginController extends ApiController{

    /**
     * Author:poptser@foxmail.com
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request){

//        $http = new Client;
//
//        $response = $http->post('/oauth/token', [
//            'form_params' => [
//                'grant_type' => 'password',
//                'client_id' => '8',
//                'client_secret' => 'aGNfF2r4QP39acCAMwVm0w0Vr22uAk8dZjg9FPJ3',
//                'username' => $request->userName,
//                'password' => $request->passWord,
//                'scope' => '',
//            ],
//        ]);
//
//        return json_decode((string) $response->getBody(), true);




//        $validator = Validator::make($request->all(), [
//            'title' => 'required|unique:posts|max:255',
//            'body' => 'required',
//        ]);
//
//        if ($validator->fails()) {
//            return redirect('post/create')
//                ->withErrors($validator)
//                ->withInput();
//        }


        $userInfo = DB::table("admin_user")->where("user_name",$request->userName)->first();
        if(!empty($userInfo)){
            if(!empty($userInfo->ec_salt)){
                $passWord=md5(md5($request->passWord).$userInfo->ec_salt);
            }else{
                $passWord=md5($request->passWord);
            }
            if($userInfo->password==$passWord){
                $sortingUser = DB::table("warehouse_personnel")->where([
                    ["uid","=",$userInfo->user_id],
                    ["status","=",1]
                ])->first();    //配货仓管端
                if(!empty($sortingUser)){
                    $apiToken = str_random(60);
                    $updateToken = DB::table('admin_user')
                        ->where('user_id', $userInfo->user_id)
                        ->update(['api_token' => $apiToken]);
                    if($updateToken==0){
                        return $this->failed("token刷新更新");
                    }else{
                        //登录成功
                        $return['token'] =  $apiToken;
                        $return['name'] =  $sortingUser->name;
                        $return['phone'] =  $sortingUser->phone;
                        $return['userType'] =  $sortingUser->position;
                        return $this->success($return,"登录成功");
                    }
                }else{
                    return $this->failedReturn("禁止登录：非移动端用户");
                }
            }else{
                return $this->failedReturn("密码错误");
            }
        }else{
            return $this->failedReturn("未找到此用户");
        }
    }
}